package com.hxzy.config.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.json.JSONUtil;
import com.hxzy.common.constans.WaimaiConst;
import com.hxzy.common.enums.AckCode;
import com.hxzy.common.util.TokenService;
import com.hxzy.common.util.WaimaiThreadLocal;
import com.hxzy.common.vo.R;
import com.hxzy.vo.LoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 验证令牌有效过滤器(Filter升级版)
 */
@Component
public class TokenValidateHandlerInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    /**
     * 在执行Controller方法之前的验证
     * @param request
     * @param response
     * @param handler 指Controller方法
     * @return  true放行,false不放行
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbiI6IjYyNmFhYmZhLWIzZGYtNGQ4ZC04MzYzLTFjYzFiNzQ2M2Y2YiJ9.NmSy1KJYK19-Ueac90HIxTjg_nuL8trw_wAv2MCkfTg
        String jwtToken= request.getHeader(WaimaiConst.AUTORIZATION);

        // 没有令牌，未登录的意思
        if(StrUtil.isBlank(jwtToken)){
            outJson(response, AckCode.JPUSH_LOGIN_ERROR);
            return false;
        }

        //jwt解密成 uuid
        String uuid=this.tokenService.jwtDecodeToUUID(jwtToken);
        //从 redis中取值
        LoginVO redisLoginVO = this.tokenService.getRedisLoginVO(uuid);
        if(redisLoginVO==null){
            outJson(response, AckCode.TOKEN_FAIL);
            return false;
        }

        //设定自动为令牌续期
        this.tokenService.refreshToken(redisLoginVO);

        //存放到本地线程池中
        WaimaiThreadLocal.loginVOThreadLocal.set(redisLoginVO);

        return true;
    }

    /**
     * 执行完Controller方法以后的操作
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
     WaimaiThreadLocal.loginVOThreadLocal.remove();
    }

    /**
     * 输出内容给前端
     * @param response
     * @param ackCode
     */
    private void outJson(HttpServletResponse response,AckCode ackCode){
        response.setCharacterEncoding("UTF-8");
        String jsonStr=JSONUtil.toJsonStr(R.build(ackCode));
        ServletUtil.write(response,jsonStr, MediaType.APPLICATION_JSON_VALUE);
    }
}
